package com.sluggard.security.manage.controller;

import com.sluggard.common.model.res.Result;
import com.sluggard.security.core.manage.SecurityUserManage;
import com.sluggard.security.manage.model.entity.RoleEntity;
import com.sluggard.security.manage.model.req.ChangePasswordReq;
import com.sluggard.security.manage.model.req.ChooseRoleReq;
import com.sluggard.security.manage.model.req.UserReq;
import com.sluggard.security.manage.model.res.MenuInfoRes;
import com.sluggard.security.manage.model.res.RoleInfoRes;
import com.sluggard.security.manage.model.vo.SecurityUser;
import com.sluggard.security.manage.service.IMenuService;
import com.sluggard.security.manage.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统信息 前端控制器
 * </p>
 *
 * @author lizheng
 * @since 2024-04-28
 */
@Tag(name = "系统信息")
@RestController
@RequestMapping("/manage/system")
public class SystemController {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private IUserService userService;

    @Resource
    private IMenuService menuService;

    @Operation(summary = "获取菜单")
    @PostMapping("menus")
    public Result<MenuInfoRes> menus(@RequestBody ChooseRoleReq req) {
        SecurityUser userInfo = SecurityUserManage.getUserInfo();
        if (userInfo.getRoles().isEmpty()) {
            return Result.error("未授权角色");
        }
        Long roleId = req.getRoleId();
        Optional<RoleEntity> optionalRole = Optional.empty();
        if (Objects.nonNull(roleId)) {
            optionalRole = userInfo
                    .getRoles()
                    .stream()
                    .filter(item -> item.getId().equals(roleId))
                    .findFirst();
            if (optionalRole.isEmpty()) {
                return Result.error("角色不存在");
            }
        } else if (Objects.nonNull(userInfo.getRoleId())) {
            optionalRole = userInfo
                    .getRoles()
                    .stream()
                    .filter(item -> item.getId().equals(userInfo.getRoleId()))
                    .findFirst();
        }
        if (optionalRole.isEmpty()) {
            optionalRole = userInfo.getRoles()
                    .stream()
                    .findFirst();
        }

        // 获取到角色
        RoleEntity roleEntity = optionalRole.get();
        userInfo.setRoleId(roleEntity.getId());

        // 如果手动选择了角色，则更用户最后选择角色
        if (req.getRoleId() != null) {
            userService.changeRole(userInfo, roleEntity);
        }

        return Result.ok(menuService.loadMenuInfo(roleEntity.getId()));
    }

    @Operation(summary = "修改密码")
    @PostMapping("changePassword")
    public Result<Void> changePassword(@RequestBody @Valid ChangePasswordReq req) {
        SecurityUser userInfo = SecurityUserManage.getUserInfo();
        if (!passwordEncoder.matches(req.oldPassword(), userInfo.getPass())) {
            return Result.error("原密码错误");
        }
        UserReq userReq = new UserReq();
        userReq.setId(userInfo.getId());
        userReq.setPassword(req.newPassword());
        userService.changePassword(userReq);
        return Result.ok("修改成功");
    }

    @Operation(summary = "获取角色")
    @PostMapping("roles")
    public Result<List<RoleInfoRes>> roles() {
        return Result.ok(SecurityUserManage.getUserInfo().getRoles().parallelStream()
                .map(item -> {
                    RoleInfoRes roleInfoRes = new RoleInfoRes();
                    roleInfoRes.setRoleId(item.getId());
                    roleInfoRes.setRoleName(item.getName());
                    return roleInfoRes;
                }).collect(Collectors.toList()));
    }

    @Operation(summary = "改变角色")
    @PostMapping("changeRole")
    public Result<Void> changeRole(@RequestBody ChooseRoleReq req) {
        if (req.getRoleId() == null) {
            return Result.error("请选择角色");
        }
        SecurityUser userInfo = SecurityUserManage.getUserInfo();

        if (userInfo.getRoles().isEmpty()) {
            return Result.error("未授权角色");
        }
        Optional<RoleEntity> optionalRole = userInfo.getRoles().stream().filter(role -> req.getRoleId().equals(role.getId())).findFirst();
        if (optionalRole.isEmpty()) {
            return Result.error("角色不存在");
        }
        RoleEntity role = optionalRole.get();
        userService.changeRole(userInfo, role);
        userInfo.setRoleId(role.getId());
        return Result.ok("修改成功");
    }
}
